package rowan.application.quickaccess.rss.parser;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;



/* 		This Xml Parser holds a parsedDataSet which contains all information retetrived from an xml feed
 * 			 
 *  	This class uses a SAX parser to read xml
 *  If you are interested in a tutorial I suggest - http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
 *  
 *  @author Tom
 */
 public class XmlParser {
	ParsedDataSet parsedDataSet;
	
	public XmlParser()
	{
	}
	
    /** 
     * Has a given Url, creates an XML reader and attempts to parse the URL with RowanRSSHandler
     * 
     *	If Successful the method displayData() is called, and creates all titles 
     *		and descriptions from the parsedDataSet
     *
     *	If we get an error a TextView is setup and displayed with information
     * @throws SAXException 
     * @throws ParserConfigurationException 
     * @throws IOException 
     */
    public void parseURL(String gUrl) throws ParserConfigurationException, SAXException, IOException
  {
	  
    	/* URL we want to load xml from */
    	URL url = new URL(gUrl);
    	
    	/* Get SAXParser from SAXParserFactory */
    	SAXParserFactory spf = SAXParserFactory.newInstance();
    	spf.setNamespaceAware(true);
    	SAXParser sp = spf.newSAXParser();
    	
    	/* Get XMLReader from SAXParser */
    	XMLReader xr = sp.getXMLReader();
    	
    	/* Create a ContentHandler to apply to the XML-Reader */
    	RowanRSSHandler myHandler = new RowanRSSHandler();
    	
    	xr.setContentHandler(myHandler); // Gives the xmlReader the handler

    	/* Parse the xml data from the URL */
    	
    	URLConnection c; 
    	c = url.openConnection();
//    	c.setConnectTimeout(3000); // stops trying to connect after 3 seconds
    	
    	xr.parse(new InputSource(c.getInputStream()));
    	/* We just parsed the url! */
    	
    	parsedDataSet = new ParsedDataSet();
    	
    	/* RowanRSSHandler now provides the parsed data */
    	parsedDataSet = myHandler.getParsedData();
    	

   }
   
	public ParsedDataSet getDataSet()
	{
		return parsedDataSet;
	}
    
    
 }